package com.entries;

import barecodes.PassesIdCoder;
import com.appclient.ControlledScreen;
import com.appclient.DaoInstanceEnum;
import com.appclient.ScreensController;
import com.carpark.ejb.DAO.DAO;
import com.carpark.ejb.Model.CarsModel;
import com.carpark.ejb.Model.ClientsModel;
import com.carpark.ejb.Model.ParkingpassesModel;
import com.carpark.ejb.Model.ParkingspacesModel;
import com.carpark.ejb.Model.ParksModel;
import com.carpark.ejb.Model.PassesrecordsModel;
import com.configurator.SpaceButton;
import java.io.IOException;
import javafx.fxml.Initializable;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import popup.PopupController;
import popup.ScanPopupController;
import spaces.Spaces;

/**
 *
 * @author Sawior
 */
public class ExitController implements Initializable, ControlledScreen {

    private ScreensController myController;
    @FXML
    private StackPane spaces;
    private SpaceButton actual;
    @FXML
    private Label personalData;
    @FXML
    private Label carPlate;
    @FXML
    private Label carData;
    @FXML
    private Label carType;
    @FXML
    private Label spaceNumber;
    private ParkingpassesModel pass;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
    }

    public void initialize() {
        Spaces spacesGetter = new Spaces(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
               actual = (SpaceButton) event.getSource();
                try {
                    System.out.println("Actual: "+actual.getId());
                   Integer space = Integer.parseInt(actual.getId());
                   checkIncommingData(null, space);
                }
                catch(Exception ex){
                    Logger.getLogger(EntryController.class.getName()).log(Level.SEVERE, "[CarPark] It isn't space...");
                }
            }
        }, Spaces.EXIT, null, null, null, null);
        spaces.getChildren().add(0, spacesGetter.getSpacesForEntries());
    }

    @Override
    public void setScreenParent(ScreensController screenParent) {
        myController = screenParent;
        initialize();
    }

    @FXML
    private void handleScanAction(ActionEvent event) {
        createScanPopup();
    }

    @FXML
    private void handleSaveAction(ActionEvent event) {
            DAO dao = DaoInstanceEnum.INSTANCE.getDao();
        if (checkScannedPass()) {
            ParkingspacesModel space = pass.getNumberId();
            space.setStatus("Free");
            dao.updateParkingSpace(space);
            dao.addPark(new ParksModel(new Date(), "Exit"), pass);
            createPopup("Dokonano wyjazdu");
            clearForm();
        }
    }

    private boolean checkScannedPass() {
        if (pass != null) {
            if (pass.getNumberId().getStatus().equals("Occupied")) {
                Date now = new Date();
                if (now.before(pass.getExpirationDate())) {
                    return true;
                }
            }
        }
        return false;
    }

    private void clearForm() {
        this.pass = null;
        this.carData.setText("");
        this.carPlate.setText("");
        this.carType.setText("");
        this.spaceNumber.setText("");
        this.personalData.setText("");
    }

    private void createScanPopup() {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getClassLoader().getResource("scanPopup.fxml"));
            AnchorPane page = (AnchorPane) loader.load();
            Stage dialogStage = new Stage();
            dialogStage.setTitle("Skanuj przepustkę");
            dialogStage.initModality(Modality.NONE);
            Scene scene = new Scene(page);
            dialogStage.setScene(scene);

            ScanPopupController controller = loader.getController();
            controller.setDialogStage(dialogStage);
            dialogStage.showAndWait();
            if(controller.getIncomming() != null && controller.getIncomming().length() > 0){
                checkIncommingData(controller.getIncomming(), null);
            }
        } catch (IOException e) {
            Logger.getLogger(EntryController.class.getName()).log(Level.SEVERE, "[CarPark] Error during handle scan popup.", e);
        }
    }

    private void checkIncommingData(String incomming, Integer id) {
        DAO dao = DaoInstanceEnum.INSTANCE.getDao();
        Integer passId;
        if(id != null){
            ParkingspacesModel space = DaoInstanceEnum.INSTANCE.getDao().getParkingSpacesByNumber(id);
            List<ParkingpassesModel> passes = DaoInstanceEnum.INSTANCE.getDao().getParkingPassBySpaceId(space);
            ParkingpassesModel pass = passes.get(passes.size()-1);
            passId = pass.getParkingPassId();
        }
        else {
            passId = PassesIdCoder.uncodeId(incomming);
        }
        if (passId != null) {
            ParkingpassesModel pass = null;
            try {
                pass = dao.getParkingPassById(passId);
            } catch (Throwable t) {
                Logger.getLogger(EntryController.class.getName()).log(Level.SEVERE, "[CarPark] Cannot load passes from database.");
                return;
            }
            if (pass != null) {
                ParkingspacesModel space = pass.getNumberId();
                if (space.getStatus().equals("Free")) {
                    createPopup("Stanowisko wolne");
                    return;
                }
                if (space.getStatus().equals("Disabled")) {
                    createPopup("Stanowisko wyłączone");
                    return;
                }
                CarsModel car = pass.getCarId();
                List<PassesrecordsModel> records = new ArrayList<>(pass.getPassesrecordsModelCollection());
                if(!records.isEmpty()){
                    ClientsModel client = records.get(0).getClientId();
                    this.personalData.setText(client.getLastName() + " " + client.getName());
                    this.carPlate.setText(car.getNumberPlate());
                    this.carData.setText(car.getMake() + ", " + car.getModel());
                    this.carType.setText(car.getCarType());
                    this.spaceNumber.setText("Stanowisko " + space.getNumber());
                    this.pass = pass;
                }
            }
        } else {
            this.personalData.setText("");
            this.carPlate.setText("");
            this.carData.setText("");
            this.carType.setText("");
            this.spaceNumber.setText("");
            createPopup("Złe dane");
        }
    }

    private void createPopup(String text) {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getClassLoader().getResource("popup.fxml"));
            AnchorPane page = (AnchorPane) loader.load();
            Stage dialogStage = new Stage();
            dialogStage.setTitle("Uwaga");
            dialogStage.initModality(Modality.WINDOW_MODAL);
            Scene scene = new Scene(page);
            dialogStage.setScene(scene);

            PopupController controller = loader.getController();
            controller.setDialogStage(dialogStage);
            controller.setPopupText(text);
            dialogStage.showAndWait();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
